#define BLINKER_WIFI
#define BLINKER_ESP_TASK

#include <Blinker.h>
#include <BLEDevice.h>
#include <BLEScan.h>
#include <BLEAdvertisedDevice.h>
#include <WiFi.h>
#include <string>
#include <SSD1306.h>
// SSD1306  display(0x3c, 21, 22);
SSD1306  display(0x3c, 15, 02);

char auth[] = "36647624b162";
// char ssid[] = "asus_new";
// char pswd[] = "1234qwer";
// char auth[] = "74e5838cc2e2";
char ssid[] = "shiguang";
char pswd[] = "1234qwer";

// 新建组件对象
BlinkerButton ButtonAtom("btn-atom");
BlinkerButton ButtonScanWifi("btn-scan-wifi");
BlinkerButton ButtonScanBLE("btn-scan-ble");
BlinkerButton ButtonShowInfo("btn-show-info");
BlinkerButton ButtonSwitchPow("btn-switch-pow");

//数字文本
BlinkerNumber AtomNum("atomNum");
BlinkerNumber TimeStampNum("timeStampNum");
BlinkerText NotiftText("tex-info");

int atomNum = 10;
int switchPowIO = 13;
bool switchPow = false;

// 按下按键即会执行该函数
void ButtonAtomCallback(const String &state) {
    atomNum++;
    showDisplay("atom "+toString(atomNum),false);
    //设置对应控制的值
    AtomNum.print(atomNum);
    TimeStampNum.print(Blinker.time());
    //往app端发送消息
    Blinker.notify("atom ok");
}

class MyAdvertisedDeviceCallbacks : public BLEAdvertisedDeviceCallbacks {
    void onResult(BLEAdvertisedDevice advertisedDevice) {
        BLINKER_LOG("find : ", advertisedDevice.toString().c_str());
    }
};

void ButtonScanBLECallback(const String &state) {
    showDisplay("BLE Scan",false);
    BLEDevice::init("");
    BLEScan *pBLEScan = BLEDevice::getScan();
    pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks(), true, false);
    pBLEScan->setActiveScan(true);
    pBLEScan->setInterval(1349);
    pBLEScan->setWindow(449);
    BLEScanResults foundDevices = pBLEScan->start(5, false);
    NotiftText.print("BLE Scan done", toString(foundDevices.getCount()));
    pBLEScan->clearResults();
    TimeStampNum.print(Blinker.time());
    Blinker.notify("BLE scan ok");
}

void ButtonScanWifiCallback(const String &state) {
    showDisplay("Wifi Scan",false);
    String list = "";
    int n = WiFi.scanNetworks();
    if (n>0) {
       for (int i = 0; i < n; ++i) {
            BLINKER_LOG(i + 1,": ",WiFi.SSID(i)," (",WiFi.RSSI(i),")");
            delay(10);
            list += WiFi.SSID(i);
            list += ",";
        }
        NotiftText.print(list, toString(n));
    }
    TimeStampNum.print(Blinker.time());
    Blinker.notify("Wifi scan ok");  
}

void ButtonShowInfoCallback(const String &state){
    // String date = "date: "+ getDateTime();
    // String runtime = "runtime: "+toString(Blinker.runTime());
    // String flashSize = "flashSize: "+toString(ESP.getFlashChipSize());
    // String flashFree = "flashFree: "+toString(ESP.getFreeSketchSpace());
    // String projectSize = "projectSize: "+toString(ESP.getSketchSize());
    // showDisplay(date+"\n"+runtime+"\n"+flashSize+"\n"+flashFree+"\n"+projectSize,false);
    ShowInfo();
}


void ButtonSwitchPowCallback(const String &state){
    switchPow=!switchPow;
    if (switchPow){
      digitalWrite(switchPowIO,HIGH);
      // showDisplay("open",false);
      ButtonSwitchPow.print("on");
    }else{
      digitalWrite(switchPowIO,LOW);
      // showDisplay("close",false);
      ButtonSwitchPow.print("off");
    }
    Blinker.notify("pow switch ok");  
}

void ShowInfo(){
    String date = "date: "+ getDateTime();
    String runtime = "runtime: "+toString(Blinker.runTime());
    String flashSize = "flashSize: "+toString(ESP.getFlashChipSize());
    String flashFree = "flashFree: "+toString(ESP.getFreeSketchSpace());
    String projectSize = "projectSize: "+toString(ESP.getSketchSize());
    showDisplay(date+"\n"+runtime+"\n"+flashSize+"\n"+flashFree+"\n"+projectSize,false);
}

String getDateTime(){
  return toString(Blinker.year())+"-"+toString(Blinker.month())+"-"+toString(Blinker.mday())+" "+toString(Blinker.hour())+":"+toString(Blinker.minute())+":"+toString(Blinker.second());
}

String toString(int n) {
     if(n==0){
       return "0";
     }
     int m = n;
     char s[100];
     char ss[100];
     int i=0,j=0;
     if (n < 0)// 处理负数
     {
         m = 0 - m;
         j = 1;
         ss[0] = '-';
     }    
     while (m>0)
     {
         s[i++] = m % 10 + '0';
         m /= 10;
     }
     s[i] = '\0';
     i = i - 1;
     while (i >= 0)
     {
         ss[j++] = s[i--];
     }    
     ss[j] = '\0';    
     return ss;
 }

void showDisplay(String text,bool init){
    if(init){
      display.init();
    }else{
      display.clear();
    }
    display.drawString(0, 0, text);
    display.display();
} 

String summary() {
    TimeStampNum.print(Blinker.time());
    AtomNum.print(atomNum);
     if (switchPow){
      ButtonSwitchPow.print("on");
    }else{
      ButtonSwitchPow.print("off");
    }
    showDisplay(getDateTime(),false);
    return "";
}

void dataRead(const String & data){  
    Blinker.vibrate(255); 
    showDisplay(data,false);
}

void setup() {
    showDisplay("server start",true);
    // 初始化串口
    Serial.begin(115200);
    BLINKER_TAST_INIT();
    //打开调试模式
    BLINKER_DEBUG.stream(Serial);
    //输出所有调试信息
    BLINKER_DEBUG.debugAll();
    // 初始化blinker
    Blinker.begin(auth, ssid, pswd);
    Blinker.attachData(dataRead);
    //注册按钮
    ButtonAtom.attach(ButtonAtomCallback);
    ButtonScanBLE.attach(ButtonScanBLECallback);
    ButtonScanWifi.attach(ButtonScanWifiCallback);
    ButtonShowInfo.attach(ButtonShowInfoCallback);
    ButtonSwitchPow.attach(ButtonSwitchPowCallback);
    Blinker.attachSummary(summary);
    pinMode(switchPowIO,OUTPUT);
    showDisplay("server start success",false);
}

void loop() {
    // Blinker.run();
    // Blinker.delay(1000);
    ShowInfo();
    // showDisplay(toString(Blinker.year())+"-"+toString(Blinker.month())+"-"+toString(Blinker.mday())+" "+toString(Blinker.hour())+":"+toString(Blinker.minute())+":"+toString(Blinker.second()));
    delay(100);
}
